<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of login
 *
 * @author Leonardo Lino
 */
class login extends CI_Controller {

    private $smarty;

    public function __construct() {
        parent::__construct();
        require_once 'smartyLoader.php';
        $this->load->library('session');
        $this->smarty = $smarty;
    }

    public function index() {

        if ($this->user->isAdmin()) {
            $this->smarty->assign("isAdmin", 1);
        } else {
            $this->smarty->assign("isAdmin", 0);
        }
        
        $utilizador = $this->session->all_userdata();
        $this->smarty->assign("nomeAdmin", $utilizador['utilizador']);

        $this->smarty->display('header.tpl.html');
        if ($this->user->isValidUser()) {
            $this->smarty->display('inicial.tpl.html');
        } else {
            $this->smarty->display('login.tpl.html');
        }
        $this->smarty->display('footer.tpl.html');
    }

    public function performLogin() {
        global $path_url;

        $ses = $this->session->all_userdata();


        if ($this->passosLogin()) {
            header( 'Location: '.$path_url ) ;
        } else {
            $this->smarty->display('header.tpl.html');
            $this->smarty->assign("isAdmin", 0);
            $this->smarty->display('login.tpl.html');
        }


        $this->smarty->display('footer.tpl.html');
    }

    public function performLogout() {
        global $path_url;
        $this->session->sess_destroy();
        header( 'Location: '.$path_url ) ;
    }

    public function passosLogin() {

        $utilizador = $this->session->userdata('username');

        if (isset($utilizador['utilizador'])) {
            // utilizador ja existe
            return true;
        } else {
            //utilizador não existe
            if (!isset($_POST['utilizador']))
                return false;

            $res = $this->user->doLogin($_POST['utilizador'], $_POST['password']);
            if (!$res or !isset($res)) {
                //NO USER with these credentials

                return false;
            } else {
                $userdata = array(
                    'utilizador' => $res['utilizador'],
                    'uid' => $res['uid'],
                    'login' => 'ok',
                    'tipo' => $res['tipo']);
                $this->session->set_userdata($userdata);
                return true;
            }
        }
    }

}

?>
